# app/admin.py
from django.contrib import admin
from .models import ScheduledTask, TaskExecutionLog, TaskMetrics


@admin.register(ScheduledTask)
class ScheduledTaskAdmin(admin.ModelAdmin):
    list_display = ['name', 'trigger_type', 'is_active', 'last_run_time', 'next_run_time', 'created_at']
    list_filter = ['trigger_type', 'is_active', 'created_at']
    search_fields = ['name', 'description', 'job_id']
    readonly_fields = ['job_id', 'last_run_time', 'next_run_time', 'created_at', 'updated_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'is_active')
        }),
        ('任务配置', {
            'fields': ('module_path', 'function_name', 'args', 'kwargs', 'max_instances')
        }),
        ('调度配置', {
            'fields': ('trigger_type', 'trigger_config')
        }),
        ('状态信息', {
            'fields': ('job_id', 'last_run_time', 'next_run_time', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )


@admin.register(TaskExecutionLog)
class TaskExecutionLogAdmin(admin.ModelAdmin):
    list_display = ['__str__', 'status', 'start_time', 'end_time', 'execution_time']
    list_filter = ['status', 'start_time', 'scheduled_task']
    search_fields = ['scheduled_task__name', 'strategy_id', 'error_message']
    readonly_fields = ['start_time', 'end_time', 'execution_time']
    
    fieldsets = (
        ('关联信息', {
            'fields': ('scheduled_task', 'strategy_id')
        }),
        ('执行状态', {
            'fields': ('status', 'start_time', 'end_time', 'execution_time')
        }),
        ('结果信息', {
            'fields': ('result', 'error_message')
        }),
    )


@admin.register(TaskMetrics)
class TaskMetricsAdmin(admin.ModelAdmin):
    list_display = ['scheduled_task', 'total_executions', 'successful_executions', 'failed_executions', 'success_rate', 'avg_execution_time']
    readonly_fields = ['total_executions', 'successful_executions', 'failed_executions', 'avg_execution_time', 'max_execution_time', 'min_execution_time', 'last_updated']
    
    def success_rate(self, obj):
        return f"{obj.success_rate:.2f}%"
    success_rate.short_description = "成功率"